package com.blockmeta.bbs.immodule.adapter;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import com.blankj.utilcode.util.LogUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blockmeta.bbs.baselibrary.net.callback.BaseResponseCallBack;
import com.blockmeta.bbs.baselibrary.utils.LoadPicUtil;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.activity.chat.CustomerServiceChatActivity;
import com.blockmeta.bbs.immodule.activity.chat.UCGChatActivity;
import com.blockmeta.bbs.immodule.activity.chat.UUChatActivity;
import com.blockmeta.bbs.immodule.bean.IMCommonLib;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.dao.ChatMessage;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.immodule.utils.ImTimeUtils;
import com.blockmeta.bbs.businesslibrary.widget.CircleGradeAndKind;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;

import java.util.List;

/**
 * Created by author on 2019/1/23.
 */

public class ImSessionListAdapter extends BaseMultiItemQuickAdapter<ChatMessage, BaseViewHolder> {

    private Context mContext;

    public ImSessionListAdapter(List<ChatMessage> data, Context context) {
        super(data);
        //人人聊天
        addItemType(ChatMessage.MSG_TYPE_UU, R.layout.item_im_talk);
        //群聊天
        addItemType(ChatMessage.MSG_TYPE_UCG, R.layout.item_im_talk);
        mContext = context;
    }

    @Override
    protected void convert(BaseViewHolder helper, ChatMessage item) {
        int itemViewType = helper.getItemViewType();

        LogUtils.i("author" + new Gson().toJson(item));
        switch (itemViewType) {
            case ChatMessage.MSG_TYPE_UU:
                //人人聊天
                initUUView(helper, item);
                break;
            case ChatMessage.MSG_TYPE_UCG:
                //群聊
                initUCGView(helper, item);
                break;
            default:
                break;
        }
    }

    //单聊
    private void initUUView(final BaseViewHolder helper, final ChatMessage item) {
        final TextView messageNum = helper.getView(R.id.talk_list_messagenum);

        if (item.getUnCheckedCount() > 0) {
            if (item.getUnCheckedCount() < 100) {
                messageNum.setText(item.getUnCheckedCount() + "");
            } else {
                messageNum.setText("99+");
            }
            messageNum.setVisibility(View.VISIBLE);
        } else {
            messageNum.setVisibility(View.GONE);
        }
        final ImageView icon = (ImageView) helper.getView(R.id.talk_list_icon);

        long userId = item.getFromId();
        switch (item.getType()) {
            case ChatMessage.TYPE_RECEIVE:
                userId = item.getFromId();
                break;
            case ChatMessage.TYPE_SEND:
                userId = item.getToId();
                break;
            default:
                break;
        }
        final TextView contentTv = helper.getView(R.id.talk_list_content);
        IMApplicationContext.getUserDomainService().getUser(userId, false, new BaseResponseCallBack<String, IMUserEntity>() {
            @Override
            public void fail(String msg) {
                LoadPicUtil.loadForIm(icon, "");
            }

            @Override
            public void success(IMUserEntity IMUserEntity) {
//                if(!TextUtils.isEmpty(IMUserEntity.getAvatarPath()) && !IMUserEntity.getAvatarPath().equals(icon.getTag())){
//                    icon.setTag(IMUserEntity.getAvatarPath());
                LogUtils.d("tingim", "refresh" + IMUserEntity.getName());
                LoadPicUtil.loadWithPicasso(icon, IMUserEntity.getAvatarPath());
//                }
                helper.setText(R.id.talk_list_name, TextUtils.isEmpty(IMUserEntity.getRemarkName()) ? IMUserEntity.getName() : IMUserEntity.getRemarkName());
                IMCommonLib.fillContentNoSpan(contentTv
                        , IMApplicationContext.getChatMessageDomainService().getShowContent(IMUserEntity, item));
            }
        });
        helper.setText(R.id.talk_list_time, ImTimeUtils.SessionListTime(item.getDate()));
        //TODO  当前只有图片聊天


        helper.addOnClickListener(R.id.btn_top)
                .addOnClickListener(R.id.btn_unread)
                .addOnClickListener(R.id.btn_delete);

        if (IMApplicationContext.getChatMessageDomainService().isMessageStick(item)) {
            helper.setText(R.id.btn_top, "取消置顶");
            helper.setBackgroundRes(R.id.talk_list_main, R.color.gray_f8f8f8);
        } else {
            helper.setBackgroundRes(R.id.talk_list_main, R.color.bg_white);
            helper.setText(R.id.btn_top, "置顶");
        }
        final long finalUserId = userId;
        helper.getView(R.id.talk_list_main).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                messageNum.setVisibility(View.GONE);
                item.setUnCheckedCount(0);
                IMApplicationContext.getUserDomainService().getUser(finalUserId, false, new BaseResponseCallBack<String, IMUserEntity>() {
                    @Override
                    public void fail(String msg) {
                        LoadPicUtil.loadForIm(icon, "");
                    }

                    @Override
                    public void success(IMUserEntity IMUserEntity) {
                        if (IMUserEntity.isCustomerService()) {
                            Intent intent = new Intent(mContext, CustomerServiceChatActivity.class);
                            intent.putExtra(Params.USER_TAG, finalUserId);
                            mContext.startActivity(intent);
                        } else {
                            Intent intent = new Intent(mContext, UUChatActivity.class);
                            intent.putExtra(Params.USER_TAG, finalUserId);
                            mContext.startActivity(intent);
                        }

                    }
                });
            }
        });

    }


    //群聊
    private void initUCGView(final BaseViewHolder helper, final ChatMessage item) {
        final TextView messageNum = helper.getView(R.id.talk_list_messagenum);
        final CircleGradeAndKind gradeAndKind = helper.getView(R.id.talk_list_group);
        gradeAndKind.setVisibility(View.VISIBLE);

        if (item.getUnCheckedCount() > 0) {
            if (item.getUnCheckedCount() < 100) {
                messageNum.setText(item.getUnCheckedCount() + "");
            } else {
                messageNum.setText("99+");
            }
            messageNum.setVisibility(View.VISIBLE);
        } else {
            messageNum.setVisibility(View.GONE);
        }
        final ImageView icon = (ImageView) helper.getView(R.id.talk_list_icon);

        final long chatGroupId = item.getChatGroupId();
        IMApplicationContext.getCircleDomainService().getGroup(chatGroupId, new BaseResponseCallBack<String, IMUserEntity>() {
            @Override
            public void fail(String msg) {
                LoadPicUtil.loadForIm(icon, "");
                helper.setText(R.id.talk_list_name, "已解散圈子");
            }

            @Override
            public void success(IMUserEntity userEntity) {
//                if(!TextUtils.isEmpty(userEntity.getAvatarPath()) && !userEntity.getAvatarPath().equals(icon.getTag())){
//                    icon.setTag(userEntity.getAvatarPath());
                LogUtils.d("tingim", "refresh" + userEntity.getName());
                LoadPicUtil.loadForIm(icon, userEntity.getAvatarPath());
//                }

                helper.setText(R.id.talk_list_name, userEntity.getName());
                helper.setGone(R.id.iv_im_sign, userEntity.isIdentification());
                gradeAndKind.setText(userEntity.getGroupLevel(), "群组");
                if (userEntity.getNoDisturb()) {
                    messageNum.setBackgroundResource(R.drawable.shape_popup_oval_8_gray);
                } else {
                    messageNum.setBackgroundResource(R.drawable.shape_popup_oval_8);
                }

            }
        });

        helper.setText(R.id.talk_list_time, ImTimeUtils.SessionListTime(item.getDate()));
        final TextView contentTv = helper.getView(R.id.talk_list_content);

        if (item.getContentType() == ChatMessage.CONTENT_TYPE_NOTIFY || item.getContentType() == ChatMessage.CONTENT_TYPE_NONOTIFY) {
            //系统提示
            IMCommonLib.fillContentNoSpan(contentTv
                    , IMApplicationContext.getChatMessageDomainService().getShowContent(null, item));
        } else {
            IMApplicationContext.getUserDomainService().getUser(item.getFromId(), false, new BaseResponseCallBack<String, IMUserEntity>() {
                @Override
                public void fail(String msg) {
                }

                @Override
                public void success(IMUserEntity IMUserEntity) {
                    IMCommonLib.fillContentNoSpan(contentTv
                            ,  IMApplicationContext.getChatMessageDomainService().getShowContent(IMUserEntity, item));
                }
            });
        }

        helper.addOnClickListener(R.id.btn_top)
                .addOnClickListener(R.id.btn_unread)
                .addOnClickListener(R.id.btn_delete);

        if (IMApplicationContext.getChatMessageDomainService().isMessageStick(item)) {
            helper.setText(R.id.btn_top, "取消置顶");
            helper.setBackgroundRes(R.id.talk_list_main, R.color.gray_f8f8f8);
        } else {
            helper.setBackgroundRes(R.id.talk_list_main, R.color.bg_white);
            helper.setText(R.id.btn_top, "置顶");
        }

        //group ID

        helper.getView(R.id.talk_list_main).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                messageNum.setVisibility(View.GONE);
                item.setUnCheckedCount(0);
                Intent intent = new Intent(mContext, UCGChatActivity.class);
                intent.putExtra(Params.USER_TAG, chatGroupId);
                mContext.startActivity(intent);
            }
        });

    }

    @Override
    public int getItemViewType(int position) {
        if (getData().size() != 0) {
            getData().get(position).setTAG_WHERE(ChatMessage.IM_LIST_TAG);
        }
        return super.getItemViewType(position);
    }

}
